package com.ibsol.database
{
	import com.ibsol.model.UserLevel;
	
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	public class LevelDAO
	{
		//Database connection
		private var _tourixDBConn:SQLConnection;
		/**
		 * Default constructor of LevelDAO
		 */
		public function LevelDAO()
		{
			_tourixDBConn = DBConnManager.getConnection("tourix");
		}
		/**
		 * Load UserLevel Objects from database
		 */
		public function loadUserLevels(resultHandler:Function, faultHandler:Function = null):void
		{
			var stmt:SQLStatement = new SQLStatement();
			stmt.sqlConnection = _tourixDBConn;
			stmt.text = "SELECT * FROM level";
			stmt.addEventListener(SQLEvent.RESULT, function(event:SQLEvent):void
			{
				resultHandler.call(this, typeArray(stmt.getResult().data));
			});
			stmt.addEventListener(SQLErrorEvent.ERROR, faultHandler == null ? sqlErrorHandler : faultHandler);
			stmt.execute();
		}
		/**
		 * Convert database obejct to UserLevel object
		 */
		private function typeObject(o:Object):UserLevel
		{
			var u:UserLevel = new UserLevel();
			u.id = o.id;
			u.lid = o.lid;
			u.levelName = o.levelName;
			return u;
		}
		/**
		 * Converts array object to UserLevel array collection
		 */
		private function typeArray(a:Array):ArrayCollection
		{
			if(a == null) return null;
			var ac:ArrayCollection = new ArrayCollection();
			for(var i:uint = 0; i<a.length; i++)
			{
				ac.addItem(typeObject(a[i]));
			}
			return ac;
		}
		/**
		 * Default SQL error handler, if above functions' fault handlers are null, this error handler is applied
		 * @param: event:SQLError	SQL Error event will be handled if there is an error
		 * @return: void
		 */
		private function sqlErrorHandler(event:SQLErrorEvent):void
		{
			mx.controls.Alert.show(event.text, "Error");
			trace(event.text);
		}

	}
}